<?php
session_start();//Start Sessions

if(isset($_SESSION['userNum'])){ //If user has already logged in, continue

	$userNum = $_SESSION['userNum']; //set userNum 
	$pageTitle = $_SESSION['title'];
	$curPos = $_SESSION['candPos']; // set the current position - preesident,vice, etc.
	$server = $_SESSION['server'];
	$user = $_SESSION['user'];
	$pass = $_SESSION['pass'];
	$db = $_SESSION['db'];

}else{

	header('Location: home.php'); //redirect to home
}

// Trick: use of voted and candnum POST method
// - The voted information from the POST method will be used for determining the position
// - the candnum information will be used for the voting process

if($_POST['voteAction'] == "Start Voting"){ //If the user has chose his candidate
	$_SESSION['candPos'] = $_POST['posNum']; //Set the session variable candPos, to be used by the curPos variable on the next time the user votes
	
	$limitReached = checkLimit($userNum,$_POST['posNum'],$server,$user,$pass,$db);//Check if the user has reached the maximum number of votes per position
	$voteClosed = checkCloseVote($server,$user,$pass,$db,$_POST['posNum']);
	
		echo "<br>Pos-".$curPos;
	echo "<br> user".$userNum;
		echo "<br>".$limitReached."limit";
	echo "<br>".$voteClosed." close";
	
		if($limitReached == 'True' || $voteClosed == 'True'){ //Self explanatory
			$case="case3"; //show end
		}else{
			$case = "case1";
		}
		
}//After this, the curPos has a value now, so it will now proceed to the voting process.


if($_POST['voteAction'] == "Vote"){ //In senatorials, if the user will pick his next vote
	
	$limitReached = checkLimit($userNum,$curPos,$server,$user,$pass,$db); //Check if user reached the limit of voting
	echo "<br>Pos-".$curPos;
	echo "<br> user".$userNum;
	$voteClosed = checkCloseVote($server,$user,$pass,$db,$_POST['posNum']);
	echo "<br>".$limitReached."limit";
	echo "<br>".$voteClosed." close";
		if($limitReached == 'True' || $voteClosed == 'True'){ //self explanatory
			
			$case = "case3";	
		}else{
			//Connect to database
			mysql_connect($server,$user,$pass) or die(mysql_error());
			mysql_select_db($db) or die(mysql_error());

			//Insert the vote to the database
			mysql_query("INSERT INTO vote_count (Voter_Number, Voted_Cand_Num) VALUES ('".$userNum."','".$_POST['candNum']."')");	
					
			$case = "case2";	
		}

	
	}
?>
<html>
<head>
<title>Vote - <?php echo $pageTitle ?></title>
<style type="text/css">
.style1 {
	border-collapse: collapse;
}
.style2 {
	border-collapse: collapse;
	background-image: url('images/bg.png');
}
</style>
</head>
<body style="background-image:url('images/bg_blue.jpg')">
<div style="position:absolute;left:75px;top: 0px">
<font face = "Arial">
<table style="width: 810px; height: 104px" border="0" cellspacing="0" cellpadding="0" class="style1">
<?php include("menuButtons.php"); ?>
</table>
<table style="width: 810px;" cellspacing="0" cellpadding="0" class="style2">
<tr>
<td style="height: 76px; width: 28px;"></td>
<td style="height: 76px" width="808px">
<?php
// User has chosen his candidates
if($case == "case2"){
echo "<br>case2";
	//connect to server
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());

	//get all candidates for the position chosen by the voter using the curPos variablee
	$result = mysql_query("SELECT c.cand_num,c.cand_name from candidates c,positions p where c.cand_pos = '".$curPos."' and c.cand_pos = p.pos_num and c.cand_num not in (select voted_cand_num from vote_count where voter_number = '".$userNum."')") or die(mysql_error());  

	//Show them all in html input, including a button for voting.
	echo "<br><h2>Vote for the position of ".$_POST['posName']."</h2>";
	echo "<table>";
	while($row = mysql_fetch_array( $result )){
		$tmpNum = $row['cand_num'];
		$tmpName = $row['cand_name'];

		//Set up a form for each row
		echo "<form action='vote.php' method='POST'>";
		echo "<input type='hidden' name='posNum' value=".$_POST['posNum'].">";
		echo "<tr><td><input type='hidden' name='candNum' value=".$tmpNum." size='1' readonly ></td>";
		echo "<td bgcolor='white'><strong>".$tmpName."</strong></td>";
		echo "<td><input type='submit' value='Vote' name='voteAction' style='width: 100px'></td></tr></form>";
		}
	echo "</table>";



}else if($case == "case1"){ //Voter has chosen the position
echo "<br>case1";
echo $_POST['posNum']."-Position";
//Connect to database
mysql_connect($server,$user,$pass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

	
	//Get all the condidates for the position using the information form the POST method form the default vote page
	$result = mysql_query("SELECT c.cand_num,c.cand_name from candidates c,positions p where c.cand_pos = '".$_POST['posNum']."' and c.cand_pos = p.pos_num and c.cand_num not in (select voted_cand_num from vote_count where voter_number = '".$userNum."')") or die(mysql_error());  

	//Show output in HTML
	echo "<br><h2>Vote for the position of ".$_POST['posName']."</h2>";
	echo "<table>";
	
	while($row = mysql_fetch_array( $result )){
		$tmpNum = $row['cand_num'];
		$tmpName = $row['cand_name'];

		echo "<form action='vote.php' method='POST'>";
		echo "<input type='hidden' name='posNum' value=".$_POST['posNum'].">";
		echo "<tr><td><input type='hidden' name='candNum' value=".$tmpNum." size='1' readonly ></td>";//This will be used for the next vote the voter will cast
		echo "<td bgcolor='white'><strong>".$tmpName."</strong></td>";
		echo "<td><input type='submit' value='Vote' name='voteAction' style='width: 100px' title = 'Vote for ".$tmpName."'></td></tr></form>";

	}	
echo "</table>";

}else if($case == "case3"){

	echo "<br><br>You have finished voting<br><a href='vote.php'>Return to voting page</a>";

}else{

//This is the default vote page code
// - Shows the positions, the number of candidates, and the max votes per position
// - Also shows whether you have finished voting or not

//Connect to database
mysql_connect($server,$user,$pass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

//Select info from positions table
$result = mysql_query("SELECT p.pos_close_vote, p.pos_num, p.pos_name, p.pos_vote_limit,count(*) as 'pos_cand_num' from positions p,candidates c where p.pos_num = c.cand_pos group by p.pos_num")
or die(mysql_error());  

//Show output in HTML
echo "<br><h2>Select a position</h2>";
echo "<form action='vote.php' method='POST'>";
echo "<table width = '670px'><tr style='background-color:silver'><td colspan ='2' width = '250px'>Position</td><td width ='200px'>No. Of Candidates</td><td width = '200px'>No. of votes allowed</td><td></td></tr>";
echo "<tr><td height='20'></td></tr>";
while($row = mysql_fetch_array( $result ))
{
		if($row['pos_close_vote'] == 0){
		
			echo "<form action='vote.php' method='POST'>";
			
			echo "<input type='hidden' name='posName' value=".$row['pos_name']." >";
			echo "<input type='hidden' name='posNum' value=".$row['pos_num'].">";
			echo "<input type='hidden' name='posCandNum' value=".$row['pos_cand_num']." >";
			echo "<input type='hidden' name='posVoteLimit' value=".$row['pos_vote_limit']." >";
			
			echo "<tr><td colspan ='2'>".$row['pos_name']."</td>";
			echo "<td align='center'>".$row['pos_cand_num']."</td>";
			echo "<td align='center'>".$row['pos_vote_limit']."</td>";

			//Check if the vote of the user from the position is already on its limit
			if(checkLimit($userNum,$row['pos_num'],$server,$user,$pass,$db) == 'True'){
				echo "<td><input style='background-color:red' type='submit' name = 'voted' value='Vote Ended' disabled><br></td></tr></form>";//Show vote ended
				//This half shows the candidates already voted by the voter
				echo "<tr><td colspan='5' style='background-color:black'><font color='white' size = '2'>Voted for ".$row['pos_name']."</font></td><tr>";
				echo "<tr style='background-color:silver'><td colspan='3'><font size = '2'>Candidate Name</td><td colspan='2'><font size = '2'>Party</td><tr>";
				
				//Get all candidates voted by voter per position
				$votedCand = mysql_query("SELECT c.cand_name, c.cand_party from candidates c, vote_count v where c.cand_num = v.voted_cand_num and v.voter_number = '".$userNum."' and c.cand_pos = '".$row['pos_num']."'");
				while($row = mysql_fetch_array( $votedCand ))
				{
					echo "<tr style='background-color:#CCFFCC'><td colspan='3'><font size = '2'>".$row['cand_name']."</td>";
					echo "<td colspan='2'><font size = '2'>".$row['cand_party']."</td></tr>";
				}
			}else{
				echo "<td><input style='background-color:#339900' type='submit' name = 'voteAction' value='Start Voting'><br></td></tr></form>";//Enable voting
			}

				
				
		}else{
			echo "<tr><td colspan='5' style='background-color:black'><font color ='red'>Voting for ".$row['pos_name']." is closed</font></td></tr>";
			}

			echo "<tr><td height='20'></td></tr>";
			
}
			
	echo "</table>";


}
//The Checklimit function
//Parameters:
//$num = voter number
// $pos = chosen position
//
//This function checks if the voter has already reached the max vote per positions
function checkLimit($num,$pos,$srvr,$usr,$passwd,$dbase){
	
	mysql_connect($srvr,$usr,$passwd) or die(mysql_error());
	mysql_select_db($dbase) or die(mysql_error());
	//voteCount determines the number of votes the user made
	$voteCount = mysql_query("Select count(*) as 'user_voted_num' from vote_count where voter_number = '".$num."' and voted_cand_num in (Select cand_num from candidates where cand_pos = '".$pos."')");
	//limitCount determines the limit per position
	$limitCOunt = mysql_query("Select p.pos_vote_limit from positions p where p.pos_num = '".$pos."'");

	while($row = mysql_fetch_array( $voteCount ))
	{
		$votesMade = $row['user_voted_num']; // get the number of votes made
	}

	while($row = mysql_fetch_array( $limitCOunt ))
	{
		$votesLimit = $row['pos_vote_limit']; // get the vote limit
	}
	
	echo "<br>".$votesMade;

	if($votesMade >= $votesLimit){ // If the votesMade is equal to votesLimit
		return 'True'; // return that the limit is reached
	}else{
		return 'False'; //limit is not reached
	}

}

function checkCloseVote($srvr,$usr,$passwd,$dbase,$posNum){

	mysql_connect($srvr,$usr,$passwd) or die(mysql_error());
	mysql_select_db($dbase) or die(mysql_error());
	//limitCount determines the limit per position
	$voteStatus = mysql_query("Select pos_close_vote from positions where pos_num = '".$posNum."'");
	while($row = mysql_fetch_array( $voteStatus ))
	{
		$status = $row['pos_close_vote']; // get the vote limit
	}
	
	if($status == 0){
	return 'False';
	}else{
	return 'True';
	}
}
?>
</td>
</tr>
</table>
<br><br><br><br><br>
</div>
<div style="position:fixed;left:72px;bottom: -5px">
<table>
<tr>
<td width="8px" colspan="2"><img src="images/end.png"></td>
</tr>
</table>
</div>
</body>
</html>
